package frame;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class Form extends JFrame {
    JLabel jlabel1;
    JLabel jlabel2;
    JLabel jlabel3;
    JTextField jtf1;
    JTextField jtf2;
    JButton jb1, jb2;
    JPanel pane;

    private String PackageConfig = "";
    private String MainKey = "";

    public String getMainKey() {
        return MainKey;
    }

    public void setMainKey(String mainKey) {
        MainKey = mainKey;
    }

    public String getPackageConfig() {
        return this.PackageConfig;
    }

    public void setPackageConfig(String packageConfig) {
        this.PackageConfig = packageConfig;
    }

    /**
     * 构造函数
     *
     * @param title
     */
    public Form(String title) {
        super(title);
        this.getContentPane().setLayout(null);
        this.setBounds(700, 300, 500, 500);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        pane = new JPanel();
        pane.setBounds(30, 30, 600, 300);
        pane.setLayout(null);
        //文本框1
        jlabel1 = new JLabel("读取文件路径:");
        jlabel1.setBounds(0, 0, 200, 200);
        //文本框2
        jlabel2 = new JLabel("查询关键字:");
        jlabel2.setBounds(0, 70, 200, 200);
        //文本框3
        jlabel3 = new JLabel("输出目录 D:\\new\\result\\result.txt");
        jlabel3.setBounds(0, 110, 200, 200);

        //这是输入框1 文件路径
        jtf1 = new JTextField();
        jtf1.setBounds(110, 90, 260, 30);
        pane.add(jlabel1);
        pane.add(jtf1);

        //这是输入框2 关键字
        jtf2 = new JTextField();
        jtf2.setBounds(110, 160, 260, 30);
        pane.add(jlabel2);
        pane.add(jtf2);

        pane.add(jlabel3);


        jb1 = new JButton("确认");
        jb1.setBounds(130, 230, 70, 30);
        pane.add(jb1);

        jb2 = new JButton("取消");
        jb2.setBounds(220, 230, 70, 30);
        pane.add(jb2);
        this.add(pane);


        /**
         * 处理文本内容
         * true 包含中文字符  false 不包含中文字符
         */
        jb1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //todo
                String inputPath = jtf1.getText().trim();
                if (inputPath.endsWith(".txt")){
                    JOptionPane.showMessageDialog(null, "输入内容不合法，应该以.txt文件结尾！！");
                } else {
                    String keyword = jtf2.getText().trim();
                    actFile(inputPath,keyword);
                    JOptionPane.showMessageDialog(null, "文件输出成功");
                }

//                //正则表达式
//                Pattern p = Pattern.compile("[\u4E00-\u9FA5|\\！|\\，|\\。|\\（|\\）|\\《|\\》|\\“|\\”|\\？|\\：|\\；|\\【|\\】]");
//                if (jtf1.getText().trim().length() == 0) {
//                    JOptionPane.showMessageDialog(null, "输入内容不能为空！！！");
//                } else {
//                    Matcher m = p.matcher(inputMainKey);
//                    if (m.find()) {
//                        JOptionPane.showMessageDialog(null, "输入内容不合法，应该为数字+英文组合！！！");
//                    } else {
//                        JOptionPane.showMessageDialog(null, "修改成功！！！");
//                    }
//                }
            }

        });

        this.setVisible(true);
    }

    /**
     * 主函数
     */
    public static void main(String[] args) {
        Form c = new Form("查找TXT中关键字");
    }

    /**
     * 读取文件
     */
    public static void actFile(String inputPath,String keyword){
//        inputPath = "D:\\new\\test";
        String outputPath = "D:\\new\\result\\result.txt";
//        keyword = "85212399-1A65-4492-985B-802A50CAEFE1";

        List<String> resultFilePaths = new ArrayList<>();
        searchFiles(inputPath, keyword, resultFilePaths);
        writeResultToFile(outputPath, resultFilePaths);

    }

    /**
     * 1 遍历文件夹
     */
    public static void searchFiles(String path, String keyword, List<String> resultFilePaths) {
        File dir = new File(path);
        File[] files = dir.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    searchFiles(file.getAbsolutePath(), keyword, resultFilePaths);
                } else if (file.isFile() && (file.getName().endsWith(".txt") || file.getName().endsWith(".TXT"))) {
                    if (containsKeyword(file, keyword)) {
                        resultFilePaths.add(file.getAbsolutePath());
                    }
                }
            }
        }
    }

    /**
     * 2 如果不是目录 则视为文件搜索关键字
     */
    private static boolean containsKeyword(File file, String keyword) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_16))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains(keyword)) {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 3 写下文件路径
     */
    private static void writeResultToFile(String outputPath, List<String> resultFilePaths) {
        //创建文件
        File outputFile = new File(outputPath);
        if (!outputFile.exists()) {
            outputFile.getParentFile().mkdirs();
            try {
                outputFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }
        //写入行数
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath))) {
            for (String filePath : resultFilePaths) {
                writer.write(filePath);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
